package com.dailyblue.java.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

// 通过反射获取到对象（调用构造器）
public class DemoB {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        // 1. 获取类
        Class c = Class.forName("com.dailyblue.java.reflection.Person");
        // 2.1 获取Person类的对象
        Person p1 = new Person();
        Person p2 = new Person(1);
        // 2.2 通过反射获取Person类的对象
        // 获取到Person类的所有构造器
        Constructor[] constructors = c.getDeclaredConstructors();
        for (Constructor c1 : constructors) {
            System.out.println(c1);
        }
        System.out.println("---------------------------------------------------------------------");
        // 获取到具体某个构造器
        Class[] 形式参数列表 = {};
        Constructor con1 = c.getDeclaredConstructor(形式参数列表);
        Constructor con2 = c.getDeclaredConstructor(Integer.class);
        Constructor con3 = c.getDeclaredConstructor(Integer.class, String.class);
        System.out.println(con1);
        System.out.println(con2);
        System.out.println(con3);
        System.out.println("---------------------------------------------------------------------");
        // 通过构造器获取类的对象
        Object obj1 = con1.newInstance();
        Object obj2 = con2.newInstance(3);
        Object obj3 = con3.newInstance(4, "admin");
        System.out.println(obj1);
        System.out.println(obj2);
        System.out.println(obj3);
    }
}
